package main

import (
	"fmt"
	"sync"
)

// for range、 管道通信
// 启动一个goroutine，生成100个数发送到ch1
// 启动一个goroutine，从ch1中取值，计算其平方到ch2中
var wg sync.WaitGroup

func f1(ch chan int) {
	defer wg.Done()
	for i := 0; i < 100; i++ {
		ch <- i
	}
	close(ch)
}

func f2(ch1 chan int, ch2 chan int) {
	defer wg.Done()
	for {
		// 判断管道是否关闭, 未关闭则取值，反之关闭for循环
		tmp, ok := <-ch1
		if !ok {
			break
		}
		ch2 <- tmp * tmp
	}
	close(ch2)
}

func main() {
	var ch1 = make(chan int, 100)
	var ch2 = make(chan int, 200)
	wg.Add(3)

	go f1(ch1)
	go f2(ch1, ch2)
	go f2(ch1, ch2)
	wg.Wait()

	for ret := range ch2 {
		fmt.Println(ret)
	}
}
